<template>
  <div style="display: flex;justify-content: space-between;text-overflow: ellipsis">
<!--    <a-menu v-model:selectedKeys="current" mode="horizontal" :click="menuPush()">-->
<!--      <a-menu-item key="menu">-->
<!--        <template #icon>-->
<!--          <appstore-outlined />-->
<!--        </template>-->
<!--        <router-link to="/question">-->
<!--          首页-->
<!--        </router-link>-->
<!--      </a-menu-item>-->
<!--      <a-menu-item key="questions">-->
<!--        <template #icon>-->
<!--          <appstore-outlined />-->
<!--        </template>-->
<!--        <router-link to="/question">-->
<!--          题库-->
<!--        </router-link>-->
<!--      </a-menu-item>-->
<!--    </a-menu>-->
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane v-for="pane in panes" :key="pane.key" :tab="pane.title" :onClick="menuPush()"></a-tab-pane>
    </a-tabs>
<!--    <a-menu v-model:selectedKeys="current" mode="horizontal">-->
<!--      <a-menu-item style="float: right;justify-content: flex-end; ">-->
      <span >
        <a-popover placement="bottomRight">
          <template v-if="userInfo.phone" #title>个人信息</template>
          <template v-if="!userInfo.phone" #title>请先登录</template>
          <template #content>
<!--            <div class="container">-->
              <div class="left-span" v-if="userInfo.phone"><a-image :width="50" :src="'http://192.168.207.128:9000/leetcode'+userInfo.pic"></a-image></div>
              <div class="right-span">
                <span v-if="userInfo.phone">昵称:{{userInfo.nickName}}</span>
                <span v-if="userInfo.phone">电话:{{userInfo.phone}}</span>
              </div>

              <p v-if="userInfo.phone">
                <a-button type="text" :onclick="openUserInfo">修改个人信息</a-button>
              </p>
              <p v-if="userInfo.phone">
                <a-button @click="logout()" type="text" danger>退出登录</a-button>
              </p>
              <p v-if="!userInfo.phone">
                <a-button @click="pushLogin()">登录</a-button>
              </p>
<!--            </div>-->
          </template>
          <a-avatar
              size="small"
              shape="circle" :src="'http://192.168.207.128:9000/leetcode'+userInfo.pic">
          </a-avatar>
        </a-popover>
      </span>
<!--      </a-menu-item>-->
<!--    </a-menu>-->


  </div>
  <a-modal v-model:visible="userInfoVisible" title="个人信息" @ok="saveUserInfo()">
    <a-form :model="userInfoDetail" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="头像">
        <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="http://localhost:8000/core/common/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
            :data="{'type':'1','data':userInfo.phone}"
        >
          <img width="50" v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="昵称">
        <a-input v-model:value="userInfoDetail.nickName" />
      </a-form-item>
      <a-form-item label="学校">
        <a-input v-model:value="userInfoDetail.school" />
      </a-form-item>
      <a-form-item label="个性签名">
        <a-input v-model:value="userInfoDetail.introduction" />
      </a-form-item>
      <a-form-item label="简单题正确率">
        <a-progress type="dashboard" :percent="userInfoDetail.questionDetail.easyCount===0?0:((userInfoDetail.questionDetail.easyCorrect/userInfoDetail.questionDetail.easyCount)*100).toFixed(2)" />
        <p>总提交数：{{userInfoDetail.questionDetail.easyCount}}</p>
        <p>正确提交数：<span style="color: #3ff53f">{{userInfoDetail.questionDetail.easyCorrect}}</span> </p>
      </a-form-item>
      <a-form-item label="中等题正确率">
        <a-progress type="dashboard" :percent="userInfoDetail.questionDetail.mediumCount===0?0:((userInfoDetail.questionDetail.mediumCorrect/userInfoDetail.questionDetail.mediumCount)*100).toFixed(2)" />
        <p>总提交数：{{userInfoDetail.questionDetail.mediumCount}}</p>
        <p>正确提交数：<span style="color: #3ff53f">{{userInfoDetail.questionDetail.mediumCorrect}}</span> </p>
      </a-form-item>
      <a-form-item label="困难题正确率">
        <a-progress type="dashboard" :percent="userInfoDetail.questionDetail.hardCount===0?0:((userInfoDetail.questionDetail.hardCorrect/userInfoDetail.questionDetail.hardCount)*100).toFixed(2)" />
        <p>总提交数：{{userInfoDetail.questionDetail.hardCount}}</p>
        <p>正确提交数：<span style="color: #3ff53f">{{userInfoDetail.questionDetail.hardCorrect}}</span> </p>
      </a-form-item>


    </a-form>
  </a-modal>

  <router-view></router-view>
</template>

<script>
import {defineComponent, h, inject, onMounted, reactive, ref, watch} from "vue";
import {useRouter} from "vue-router";
import axios from "axios";
import {isReturnTrue, reload} from "@/util/util";
import {MailOutlined, AppstoreOutlined, SettingOutlined, PlusOutlined, LoadingOutlined} from '@ant-design/icons-vue';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default defineComponent({
  components: {
    LoadingOutlined,
    PlusOutlined,
  },
  setup(){
    const pushLogin=()=>{
      router.push('/login')
    }
    const userInfo=reactive({
      phone:JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).phone,
      pic:JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).pic,
      nickName:JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).nickName,
      token:JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).token,
    }
    );
    const router = useRouter();
    let panes = ref([{
      key:'',
      title:'',
      route:''
    }]);
    const activeKey = ref('1');
    watch(() =>
            router.currentRoute.value.path,
        (toPath,oldValue) => {
            // console.log("用户"+window.localStorage.getItem("USERINFO"))
            //要执行的方法
            console.log("路由改变"+oldValue);
            getPic()
            userInfo.phone=JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).phone;
            userInfo.nickName=JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).nickName;
            userInfo.token=JSON.parse(window.localStorage.getItem("USERINFO"))==null?null:JSON.parse(window.localStorage.getItem("USERINFO")).token;
          activeKey.value='1'
          getMenu()
            },{immediate: false,deep: true});
    const menuPush=()=>{
      console.log("activeKey"+activeKey.value)
      for (let i = 0; i < panes.value.length; i++) {
        if(activeKey.value===panes.value[i].key){
          console.log(panes.value[i].route);
          router.push(panes.value[i].route);
          activeKey.value='undefined';
          break;
        }
      }
    }
    const getPic=()=>{
      axios.get("/core/sys-user/getPic").then((response)=>{
        if(isReturnTrue(response.data.code)){
          userInfo.pic=response.data.data
        }
        else{
          alert(response.data.message)
        }
      })
    }
    const config={
      headers:{
        'Authorization':userInfo.token
      }};
    const getMenu=()=>{
      let phone='';
      if(userInfo.phone!=null){
        phone=userInfo.phone;
      }
      axios.get("http://localhost:8000/core/sys-user/getResource?type=1&phone="+phone,config).then((response)=>{
        if(isReturnTrue(response.data.code)){
          panes.value=response.data.data;
        }
        else{
          alert(response.data.message);
        }
      })
      console.log("菜单资源")
      console.log(panes.value)
    }
    const logout=()=>{
      axios.get("/core/sys-user/logout").then((response)=>{
        if(isReturnTrue(response.data.code)){
          window.localStorage.setItem("USERINFO",null)
          alert("登出成功")
          router.push('/login')
        }
        else{
          alert(response.data.message)
        }
      })
    };
    const userInfoVisible=ref(false)
    const openUserInfo=()=>{
      queryUserInfo();
      userInfoVisible.value=true
    }
    const queryUserInfo=()=>{
      axios.get("/core/sys-user/userInfo").then((response)=>{
        if(isReturnTrue(response.data.code)){
          userInfoDetail.phone=response.data.data.phone
          userInfoDetail.nickName=response.data.data.nickName
          userInfoDetail.school=response.data.data.school
          userInfoDetail.introduction=response.data.data.introduction
          userInfoDetail.questionDetail.easyCorrect=response.data.data.easyCorrect==null?0:response.data.data.easyCorrect
          userInfoDetail.questionDetail.easyCount=response.data.data.easyCount==null?0:response.data.data.easyCount
          userInfoDetail.questionDetail.mediumCorrect=response.data.data.mediumCorrect==null?0:response.data.data.mediumCorrect
          userInfoDetail.questionDetail.mediumCount=response.data.data.mediumCount==null?0:response.data.data.mediumCount
          userInfoDetail.questionDetail.hardCorrect=response.data.data.hardCorrect==null?0:response.data.data.hardCorrect
          userInfoDetail.questionDetail.hardCount=response.data.data.hardCount==null?0:response.data.data.hardCount
          imageUrl.value='http://192.168.207.128:9000/leetcode/'+response.data.data.pic

        }
        else{
          alert(response.data.message)
        }
      })
    }
    const saveUserInfo=()=>{
      axios.post("/core/sys-user/saveDetail",{
        'nickName':userInfoDetail.nickName,
        'school':userInfoDetail.school,
        'introduction':userInfoDetail.introduction,
        'pic':userInfoDetail.pic
      }).then((response)=>{
        if(isReturnTrue(response.data.code)){
          alert("保存成功")
          userInfoVisible.value=false;
          getPic()
        }else{
          alert(response.data.message)
        }
      })
    }
    const userInfoDetail=reactive({
      nickName:'',
      pic:'',
      phone:'',
      school:'',
      introduction:'',
      questionDetail:{
        easyCount:'',
        easyCorrect:'',
        mediumCount:'',
        mediumCorrect:'',
        hardCount:'',
        hardCorrect:'',
      }
    });
    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref();
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        console.log("返回值")
        console.log(info.file.response.data)
        userInfoDetail.pic=info.file.response.data
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, base64Url => {
          imageUrl.value = base64Url;
          loading.value = false;
        });
      }
      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };
    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    };
    const  uploadFile=(file)=>{
      console.log(file)
    }
    onMounted(()=>{
      activeKey.value='undefined';
      console.log("menu"+userInfo.phone);
      getMenu();
      getPic()
    })
    return{
      uploadFile,
      userInfo,
      saveUserInfo,
      userInfoDetail,
      activeKey,
      panes,
      menuPush,
      config,
      logout,
      pushLogin,
      userInfoVisible,
      openUserInfo,
      queryUserInfo,
      labelCol: {
        style: {
          width: '150px',
        },
      },
      wrapperCol: {
        span: 14,
      },
      fileList,
      loading,
      imageUrl,
      handleChange,
      beforeUpload,
      getPic
    };
  }
});
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;

}

.left-span {
  margin-right: 10px; /* 可选：设置左右间距 */
}

.right-span {
  display: flex;
  flex-direction: column;
}

.right-span span {
  margin-bottom: 1px; /* 可选：设置上下间距 */
}
</style>
